#!/bin/bash
#Description install redis-4.0.8
SOFTDIR=/usr/local/src
REDISVERSION=4.0.8
REDISPATH=/usr/local/redis-${REDISVERSION}
BINDIP=$(/sbin/ifconfig eth1|grep inet|grep -v inet6|awk '{print $2}')
REDISDIR=/data/redis
PORT1=6380
PORT2=6381
PORT3=6382
REDISCONFNAME=redis.conf
USER=redis
GROUP=redis
# create redis user
if ! id $USER &>/dev/null;then
        groupadd -g 1211 $GROUP
        useradd -u 1211 -g $GROUP -s /sbin/nologin $USER
fi
#create directroy
for i in ${PORT1} ${PORT2} ${PORT3};do
	[ ! -d ${REDISDIR}/$i ] && mkdir -p ${REDISDIR}/$i/{conf,db,log} && chown -R $USER:$GROUP ${REDISDIR}/$i/{db,log}
done
#install jemalloc
yum -y install jemalloc
#download redis and install redis
cd $SOFTDIR && [ ! -f redis-${REDISVERSION}.tar.gz ] && wget http://download.redis.io/releases/redis-4.0.8.tar.gz
[ ! -d redis-${REDISVERSION} ] && tar xf redis-${REDISVERSION}.tar.gz
cd redis-${REDISVERSION} && make PREFIX=${REDISPATH} install

#copy redis configure file redis
for port in ${PORT1} ${PORT2} ${PORT3};do
   cat > ${REDISDIR}/${port}/conf/redis.conf <<EOF
	################################## NETWORK #####################################
	bind $BINDIP
	protected-mode yes
	port $port
	tcp-backlog 511
	timeout 0
	tcp-keepalive 300
	################################# GENERAL #####################################
	daemonize yes
	supervised no
	pidfile ${REDISDIR}/${port}/redis.pid
	loglevel notice
	logfile ${REDISDIR}/${port}/log/redis.log
	databases 20
	################################ SNAPSHOTTING  ################################
	save 900 1
	save 300 10
	save 60 10000
	stop-writes-on-bgsave-error yes
	rdbcompression yes
	rdbchecksum yes
	dbfilename dump.rdb
	dir ${REDISDIR}/${port}/db/
EOF
done
#configure redis start script
for port in ${PORT1} ${PORT2} ${PORT3};do
	cd ${REDISPATH} && bin/redis-server ${REDISDIR}/${port}/conf/redis.conf
done
